package org.example.util;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpUtil {

    //获取下载文件大小
    public static long getHttpFileContentLength(String url) throws IOException {

        HttpURLConnection httpURLConnection = null;
        int contentLength;

        try{
            httpURLConnection = getHttpURLConnection(url);
            contentLength = httpURLConnection.getContentLength();
        }finally {
            if (httpURLConnection != null){
                httpURLConnection.disconnect();
            }
        }
        return contentLength;

    }


    public static HttpURLConnection getHttpURLConnection(String url,long startPos,long endPos) throws IOException {

        HttpURLConnection httpURLConnection = getHttpURLConnection(url);
        LogUtil.info("下载的区间是：（） ---  （）",startPos,endPos);

        if (endPos != 0 ){
            httpURLConnection.setRequestProperty("RANGE" ,"bytes=" + startPos + "---" + endPos);
        }else {
            httpURLConnection.setRequestProperty("RANGE", "bytes=" + startPos +  "---");
        }
        return httpURLConnection;
    }

    public static HttpURLConnection getHttpURLConnection(String url) throws IOException {

        URL httpURL = new URL(url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) httpURL.openConnection();
        httpURLConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50");
        return httpURLConnection;
    }

    public static String getHttpFileName(String url){

        int index = url.lastIndexOf("/" );
        String fileName = url.substring(index + 1);
        //System.out.println("该链接下载的文件名称是："+ fileName);
        return fileName;

    }

}
